import { redirect, useRouter } from "next/navigation";
import { getMyPosts } from "./actions";
import { revalidatePath } from "next/cache";
import PostSummaryList from "@/components/post-summary-list";
import Pagination from "@/components/pagination";
import ErrorInfo from "@/components/error-info";

type PageProps = {
  searchParams: { page?: string; size?: string };
};

export default async function MyPosts({ searchParams }: PageProps) {
  const page = +(searchParams.page || "1");
  const size = +(searchParams.size || "10");

  const $myPosts = await getMyPosts(page, size);
  if ($myPosts.ok) {
    return (
      <div>
        <PostSummaryList posts={$myPosts.data.posts} />
        <Pagination
          page={page}
          size={size}
          totalPage={Math.ceil($myPosts.data.count / size)}
          jumpTemplate={(page, size) => `/me/posts?page=${page}&size=${size}`}
        />
      </div>
    );
  } else if ($myPosts.code === "ERR_UNAUTHENTICATED") {
    revalidatePath("/me/posts");
    redirect("/login");
  } else {
    return <ErrorInfo code={$myPosts.code} message={$myPosts.message} />;
  }
}
